#!/bin/bash

SUDO=sudo

pins="4 17 27"

declare -A color
color["r"]="4"
color["g"]="17"
color["b"]="27"
color["y"]="4 17"
color["c"]="17 27"
color["m"]="4 27"
color["w"]="4 17 27"
color["x"]=""

function led_start () {
    if [[ $(whoami) != "root" ]]
    then
	$SUDO $0 start
    else
	for pin in $pins
	do
	    [[ -d /sys/class/gpio/gpio${pin} ]] || echo $pin >/sys/class/gpio/export
	    echo out >/sys/class/gpio/gpio${pin}/direction
	    chmod a=rw /sys/class/gpio/gpio${pin}/value
	done
    fi
}

function led_stop () {
    if [[ $(whoami) != "root" ]]
    then
	$SUDO $0 stop
    else
	for pin in $pins
	do
	    [[ -d /sys/class/gpio/gpio${pin} ]] && echo $pin >/sys/class/gpio/unexport
	done
    fi
}

function led_off () {
    for pin in $pins
    do
	echo 0 >/sys/class/gpio/gpio${pin}/value
    done
}

function led_color () {
    led_off
    for pin in ${color[${1:0:1}]}
    do
	echo 1 >/sys/class/gpio/gpio${pin}/value
    done
}

function led_blink () {
    step=${2:-0.2}
    i=0
    while [[ $i -lt ${#1} ]]
    do
        led_color ${1:$i:1}
        sleep $step
        i=$((i+1))
    done
    led_off
}

if [[ $# -gt 0 ]]
then
    case $1 in
        start) led_start ;;
        stop)  led_stop ;;
        off)   led_off ;;
        color)
	    if [[ $# -lt 2 ]]
	    then
		echo >&2 "usage: $0 color COLOR"
		exit 1
	    fi
	    led_color $2
	    ;;
        blink)
	    if [[ $# -lt 2 ]]
	    then
		echo >&2 "usage: $0 blink COLORS [TIME]"
		exit 1
	    fi
	    led_blink $2 $3
	    ;;
        *)  echo >&2 "$0: invalid subcommand: must be start, stop, off, color, blink"
    	    exit 1
    	    ;;
    esac
fi
